"use client";

import { useState, useEffect, useRef, useCallback } from 'react';
import Link from 'next/link';

export const Mainbar = () => {
    const [showNavbar, setShowNavbar] = useState(true); // 控制导航栏的显示/隐藏
    const lastScrollY = useRef(0); // 使用 useRef 存储滚动位置，避免重渲染时丢失状态

    const handleScroll = useCallback(() => {
        const currentScrollY = window.scrollY;

        if (currentScrollY > lastScrollY.current && showNavbar) {
            setShowNavbar(false); // 向下滚动 -> 隐藏导航栏
        } else if (currentScrollY < lastScrollY.current - 2 && !showNavbar) {
            setShowNavbar(true); // 向上滚动 -> 显示导航栏
        }

        lastScrollY.current = currentScrollY; // 更新上次滚动位置
    }, [showNavbar]); // 依赖于 showNavbar，避免不必要的状态更新

    useEffect(() => {
        window.addEventListener("scroll", handleScroll);

        return () => {
            window.removeEventListener("scroll", handleScroll);
        };
    }, [handleScroll]); // 依赖 handleScroll，确保事件监听器始终是最新的

    return (
        <nav
            className={`bg-[#f6f8f9] rounded-full text-black p-5 shadow-md fixed 
            inset-x-0 mx-auto w-[70%] max-w-[450px]
            m-3 transition-transform duration-300 
            ${showNavbar ? 'translate-y-0' : '-translate-y-[200%]'}`}
        >
            <ul className="flex justify-center items-center  w-full">
                <li>
                    <Link href="/" className="hover:text-yellow-400">书城</Link>
                </li>
                <li className='mx-5'>
                    <Link href="/collect" className="hover:text-yellow-400">我的书架</Link>
                </li>
                <li>
                    <Link href="/my" className="hover:text-yellow-400">我的</Link>
                </li>
            </ul>
        </nav>


    );
};


